#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

import os
from fm_util import Util, SingletonProcess
from fm_param import FmConst
from usr_checker import FmUsrChecker
from usr_cleaner import FmUsrCleaner
from usr_session import UsrSession


class FmMain:

    def doShow(self):
        '''
        >>> Example:

        Linux Kernel Core Dump:
            Enabled

        Current Session:
            ID - seat-main, Access - physical, Ui - gui, Business - ecenter

        '''

        FmUsrChecker().basicCheck()

        print("Current Session:")
        # FIXME
        print("")

        return 0

    def doCoreDump(self, bEnable):
        coreDumpEnableFile = os.path.join(FmConst.cfgDir, "enable-coredump")
        if bEnable:
            Util.ensureAncesterDir(coreDumpEnableFile)
            Util.touchFile(coreDumpEnableFile)
        else:
            Util.forceDelete(coreDumpEnableFile)

    def doCheck(self, bAutoFix):
        FmUsrChecker().fullCheck(bAutoFix, False)
        return 0

    def doClean(self, bPretend):
        FmUsrChecker().basicCheck()
        FmUsrCleaner().clean(bPretend)
        return 0

    def doSession(self, access, ui, business):
        if access == "physical":
            sessionId = "seat-main"
        else:
            sessionId = "0"

        os.makedirs(FmConst.getRunDir(sessionId), exist_ok=True)
        try:
            with SingletonProcess(FmConst.getSingletonLockFile(sessionId)):
                Util.forceDelete(FmConst.getTmpDir(sessionId))
                os.makedirs(FmConst.getTmpDirOnHdd(sessionId), exist_ok=True)
                UsrSession(sessionId, access, ui, business).run()
                return 0
        except SingletonProcess.AlreadyExistException:
            print("Another usrman session manager is running.")
            return 1
        finally:
            Util.forceDelete(FmConst.getTmpDirOnHdd(sessionId))
            Util.forceDelete(FmConst.getTmpDir(sessionId))
